<template>
  <div  v-loading="loading">
    <el-steps :active="active" align-center>
      <el-step v-for="(item, index) in tabSteps" :key="index" :title="item.label" :description="item.description" />
    </el-steps>
    <div class="active-box" v-show="fileStatus != 2">
      <div class="active-item tc mt10" v-for="item in tabSteps" :key="item.active">
        <div class="active-content" v-show="active == item.active">
          <el-descriptions :title="active == 1 ? '请点击此处' : ''" :column="1">
            <template #extra>
              <el-button v-if="item.download" @click="handleDownload(item)"> 下载文件 </el-button>
            </template>
            <el-descriptions-item v-for="(rule, ruleIndex) in item.rules" :key="ruleIndex">
              <template #label>
                <div class="cell-item">
                  {{ rule.label }}
                </div>
              </template>
              <ul class="tl rule-content">
                <li v-for="chi in rule.children" :key="chi.label">
                  <el-link v-if="chi.link" @click="handleDownload(chi)">
                    {{ chi.label }}
                  </el-link>
                  <span v-else> {{ chi.label }}</span>
                </li>
              </ul>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <div class="active-upload" v-if="active > 1">
        <el-upload ref="uploadRef" drag :auto-upload="false" action="" :limit="1" :on-exceed="handleExceed"
          :on-change="onFileChange" :http-request="onHttpRequest">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            点击或将<em>《{{ nowData.uploadTip }}》</em>拖拽到这里上传
          </div>
          <template #tip>
            <div class="el-upload__tip">请上传xlsx格式的文件</div>
            <el-progress :text-inside="true" v-show="percent > 0" :stroke-width="20" :percentage="percent" />
          </template>
        </el-upload>
      </div>
    </div>

    <div class="active-sure-btn tc" v-if="fileStatus == 1">
      <el-button @click="handleClear">重新提交</el-button>
      <el-button type="primary" @click="submitUpload">确认并开始导入</el-button>
    </div>
    <div class="active-success tc" v-else-if="fileStatus == 2">
      <!-- 添加导入详情 -->
      <DataGather :dataType="dataType" :gatherObj="gatherObj" :nextBtn="false"></DataGather>
      <el-button v-show="active < tabSteps.length" class="ap-btn" type="primary" @click="next(fileStatus)"> 下一步
      </el-button>
      <el-button class="ap-btn" type="primary" @click="handleClear" v-show="active == tabSteps.length"> 再次采集 </el-button>
      <el-button class="ap-btn" type="primary" @click="handleBack" v-show="active == tabSteps.length"> 返回 </el-button>
    </div>
    <div class="active-btn tc" v-else>
      <el-button class="ap-btn" type="primary" @click="back" v-show="active > 1"> 上一步 </el-button>

      <el-button class="ap-btn" type="primary" @click="next" v-show="active < tabSteps.length"> 跳过，下一步 </el-button>
      <el-button class="ap-btn" type="primary" @click="handleBack" v-show="active == tabSteps.length"> 完成 </el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { UploadFilled } from '@element-plus/icons-vue'
import FileSaver from 'file-saver'
import DataGather from '@/views/datacenter/components/DataGather/result.vue'
import type { UploadProps, UploadInstance, UploadRawFile } from 'element-plus'

const emit = defineEmits(['refreshPage'])
const uploadRef = ref<UploadInstance>()
const apiMod: any = inject('apiMod')
type Props = {
  tabSteps?: any,
  dataType?: string | number
}
const props = withDefaults(defineProps<Props>(), {
  tabSteps: [],
  dataType: 99,
})
const fileStatus = ref(0)
const percent = ref(0)
const nowData: any = ref({})
const active: any = ref(1)
const gatherObj = ref({})
const loading = ref(false)
const handleClear = () => {
  uploadRef.value!.clearFiles()
  fileStatus.value = 0
  percent.value = 0
}

const next = (status) => {
  if (status == 2) {
    fileStatus.value = 0
    handleClear()
  }
  active.value++
  nowData.value = props.tabSteps[active.value - 1]
}
const back = () => {
  active.value--
  nowData.value = props.tabSteps[active.value - 1]
}

const handleBack = () => {
  fileStatus.value = 0
  handleClear()
  emit('refreshPage')
}
const onFileChange = async (file) => {
  if (file.status == 'ready') {
    fileStatus.value = 1
  }
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = new Date().getTime()
  uploadRef.value!.handleStart(file)
  uploadRef.value!.submit()
}
// 上传文件
const onHttpRequest = async (options) => {
  try {
    const form = new FormData()
    form.append('file', options.file)
    form.append('code', nowData.value.code)
    const data = await apiMod[nowData.value.url](form, (progressEvent) => {
      percent.value = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(1))
    })
    loading.value = false 
    if (data.code == 0 && data.data) {
      fileStatus.value = 2
      gatherObj.value = data.data
    }
    // emit('refreshPage')
  } catch (error) {
    fileStatus.value = 2
    loading.value = false 
  }
}
const submitUpload = () => {
  loading.value = true 
  uploadRef.value!.submit()
}
// 下载模板
const handleDownload = (item) => {
  if (item.url) {
    apiMod[item.url]().then((res) => {
      FileSaver.saveAs(res, item.label + '.xlsx')
    })
  } else {
    const linkItem = item.rules[0].children
    const requestApi = linkItem.map((item) => {
      return apiMod[item.url]()
    })
    Promise.all([...requestApi]).then((res) => {
      res.map((item, index) => {
        FileSaver.saveAs(item, linkItem[index].label + '.xlsx')
      })
    })
  }
}
</script>

<style scoped lang="scss">
.active-box {
  width: 30vw;
  margin: 0 auto;

  .rule-content {
    background: #f5f5f5;
    border-radius: 7px;
    border: 1px solid #d9d9d9;
    padding: 15px;
  }

  .active-sure-btn {
    width: inherit;
  }
}
</style>
